package com.librelato.persistencia;

import java.util.ArrayList;
import java.util.List;

import com.librelato.bean.CentroCustoBean;
import com.librelato.persistencia.config.SQLConfiguracao;
import com.librelato.persistencia.enums.EnumCondicao;
import com.librelato.persistencia.interfaces.ICentroCustoDao;

public class CentroCustoDao<P extends CentroCustoBean> extends DaoGenerico<P>
		implements ICentroCustoDao<P> {

	@Override
	public String procuraPorParam(String tabela, String campo, String valor,
			EnumCondicao condicao) {
		return null;
	}

	@Override
	public P salvar(P p) {
		return null;
	}

	public void editar(P p) throws Exception {
	};

	public void excluir(P p) throws Exception {
	};

	@Override
	public void preSalvar(P p) {
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<P> buscaCentrosCusto(String filial,String nome, int tipo) throws Exception {
		conn = null;
		ps = null;
		rs = null;
		query = null;
		List<CentroCustoBean> listaCentros = new ArrayList<CentroCustoBean>();
		CentroCustoBean centro;

		try {
			conn = GerenciadorConexao.getConexao();
			if (tipo == 2) {
				query = SQLConfiguracao.getInstance().getValor(
						"localiza_centros");
				query += "AND ZPT_CUSTO LIKE UPPER(?)";
			} else if (tipo == 1) {
				query = SQLConfiguracao.getInstance().getValor(
						"localiza_centros");
				query += "AND ZPT_DESCR LIKE UPPER(?)";
			}
			ps = conn.prepareStatement(query);
			ps.setString(1, filial);
			ps.setString(2, "%%" + nome.toUpperCase() + "%%");
			rs = ps.executeQuery();
			while (rs.next()) {
				centro = new CentroCustoBean();
				centro.setCodigo(rs.getString("ZPT_CUSTO"));
				centro.setDescricao(rs.getString("ZPT_DESCR"));
				centro.setFilial(rs.getString("ZPT_FILIAL"));
				listaCentros.add(centro);
			}
			return (List<P>) listaCentros;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			super.fecharRecursos(ps, rs);
		}
	}

	@Override
	public CentroCustoBean verificaCentroCusto(CentroCustoBean centroCusto)
			throws Exception {
		conn = null;
		ps = null;
		rs = null;
		query = null;

		CentroCustoBean centro = null;
		try {
			conn = GerenciadorConexao.getConexao();
			query = SQLConfiguracao.getInstance().getValor("localiza_centro");
			ps = conn.prepareStatement(query);
			ps.setString(1, centroCusto.getFilial());
			ps.setString(2, centroCusto.getCodigo());
			rs = ps.executeQuery();
			if (rs.next()) {
				centro = new CentroCustoBean();
				centro.setFilial(rs.getString("ZPT_FILIAL"));
				centro.setCodigo(rs.getString("ZPT_CUSTO"));
				centro.setDescricao(rs.getString("ZPT_DESCR"));
			}
			centroCusto = null;
			return centro;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			super.fecharRecursos(ps, rs);
		}
	}
}
